package view.graph
{
	import flash.events.Event;
	
	import model.ds.LineSeriesData;
	
	import mx.binding.utils.BindingUtils;
	import mx.charts.series.LineSeries;
	import mx.collections.ArrayCollection;
	import mx.containers.Canvas;
	import mx.containers.HBox;
	import mx.containers.VBox;
	import mx.events.FlexEvent;
	import mx.events.ResizeEvent;
	import mx.formatters.CurrencyFormatter;
	import mx.states.AddChild;
	import mx.utils.ObjectUtil;
	
	import spark.components.Label;
	import spark.primitives.Graphic;
	
	public class CustomLineChart extends Canvas
	{
		protected var legendWidth:int = 0;
		
		private var _graphData:ArrayCollection;
		
		protected var _data:*;
		protected var maxValue:Number = 0;
		private var _seriseFieldName:Array 		= new Array;
		private var _seriseDisPlayName:Array 	= new Array;
		
		private var _strokeArray:Array 			= [0x4ce025,0xffba00,0x00baff,0xff0037];
		private var TitleViewNum:int = 4;
		private var _totalLine:int = 3;
		
		private var _seriseData:Vector.<LineSeriesData> = new Vector.<LineSeriesData>; 

		private var legendHBox:HBox;
		private var axisHBox:HBox;
		private var axisVBox:Canvas;
		
		private var _topmargin:int = 2;
		
		private var _xgap:int = 40;
		private var ygap:int = 42;
		private var rgap:int = 0;
		private var sector:int = 6;
		private var graphWidth:Number = width - xgap;
		private var graphHeight:Number= height - ygap;

		private var bgHeight:Number;

		private var hAxiwWidth:int = 60;
		protected var zeroView:Boolean = false;
		
		
		public function CustomLineChart()
		{
			super();
			addEventListener(FlexEvent.CREATION_COMPLETE,onCreate)
			addEventListener(Event.RESIZE, resizeHandler);
			this.horizontalScrollPolicy = "off";
			this.verticalScrollPolicy = "off";
			
			
			axisHBox = new HBox();
			axisHBox.horizontalScrollPolicy = "off";
			axisHBox.verticalScrollPolicy = "off";
			axisHBox.setStyle("horizontalGap",0)
			addChild(axisHBox);
			
			
			axisVBox = new Canvas();
			axisVBox.horizontalScrollPolicy = "off";
			axisVBox.verticalScrollPolicy = "off";
			//axisVBox.setStyle("verticalGap",0)
			
			addChild(axisVBox);
			
		}
		
		public function get topmargin():int
		{
			return _topmargin;
		}


		public function get xgap():int
		{
			return _xgap;
		}

		public function set xgap(value:int):void
		{
			_xgap = value;
		}

		public function get seriseData():Vector.<LineSeriesData>
		{
			return _seriseData;
		}
		
		
		public function get strokeArray():Array
		{
			return _strokeArray;
		}
		
		public function set strokeArray(value:Array):void
		{
			_strokeArray = value;
		}
		
		public function get seriseFieldName():Array
		{
			return _seriseFieldName;
		}
		public function get seriseDisPlayName():Array
		{
			return _seriseDisPlayName;
		}
		
		public function get graphData():ArrayCollection
		{
			return _graphData;
		}

		protected function resizeHandler(event:ResizeEvent):void
		{
			
			drawGraph();
		}

		public function set graphData(value:ArrayCollection):void
		{
			_graphData = value;
		}

		protected function setSeeiseData():void
		{
			for (var i:int = 0;i<seriseFieldName.length;i++)
			{	
				var lineSd:LineSeriesData = new LineSeriesData;
				lineSd.data = seriseFieldName[i];
				lineSd.displayName = seriseDisPlayName[i]? seriseDisPlayName[i] :seriseFieldName[i];
				_seriseData.push(lineSd);
			}
			
		}
		protected function onCreate(event:FlexEvent):void
		{
			setSeeiseData();
			createLegend();
			drawGraph();
		}
		protected function setMaxValue(...args):Number
		{
			var max:Number = 0;
			for (var v:* in args)
			{
				
				var num:Number = Number(args[v])
				if(!isNaN(num))
					max = Math.max(max, args[v])
			}
			
			//trace("max",max)
			return max;
		}
		
		
		
		private function createLegend():void
		{
			if(legendHBox)
				return;
			legendHBox = new HBox;
			addChild(legendHBox)
			legendHBox.height = 24;
			legendHBox.setStyle("bottom" , "0");
			legendHBox.setStyle("backgroundColor" , "#eaedf2");
			legendHBox.horizontalScrollPolicy = "off";
			legendHBox.verticalScrollPolicy = "off";
			legendHBox.horizontalCenter = 0;
			for(var i:int = 0;i<seriseDisPlayName.length;i++)
			{
				
				var legend:CustomLegend = new CustomLegend;
				legend.color = strokeArray[i];
				legend.title = seriseDisPlayName[i];
				legendHBox.addChild(legend);
			}
			legendHBox.width = legendWidth;
		}
		
		public function setGraphData($data:*):void
		{
			if(graphData)
				graphData.removeAll();
			graphData= new ArrayCollection();
			var c:int = 0;
			
			_data = $data;
			if($data.hasOwnProperty("time"))
				c = _data.time.length;
			
			for(var i:int = 0;i<c;i++)
			{
				
				var obj:Object = getGraphObject(i);
				
				graphData.addItem(obj)
			}
			drawGraph();
		}
		private function createGraphBg():void
		{
			// TODO Auto Generated method stub
			//trace(this.name,"width",width,"height",height)
			graphWidth= width - xgap;
			graphHeight= height -topmargin- ygap;
			
			graphics.clear();
			
			graphics.moveTo(xgap,0);
			graphics.beginFill(0xe1e1e1);
			
			bgHeight = graphHeight / sector
			for(var i:int = 0;i<sector;i++)
			{
				if(i%2== 0)
					graphics.drawRect(xgap, topmargin+bgHeight*i , graphWidth-rgap ,bgHeight);
			}
			graphics.endFill();
			
			graphics.lineStyle(1,0x444444);
			graphics.moveTo(xgap,topmargin);
			graphics.lineTo(xgap,topmargin+graphHeight);
			graphics.lineTo(width-rgap,topmargin+graphHeight);
			
			
			
		}
		protected function drawGraph():void
		{
			
			createGraphBg();
			if(!graphData)
				return;
			if(graphData.length==0)
				return;
			var lineYPoint:Number = graphHeight/maxValue;
			var lineXPoint:Number = graphWidth/graphData.length;
			
			axisVBox.height = graphHeight+bgHeight;
			axisVBox.width = xgap;
			//axisVBox.y = 0;
			
			axisHBox.height = 18;
			axisHBox.width = graphWidth;
			axisHBox.x = xgap;
			axisHBox.y = topmargin+graphHeight;
			/**
			 * text="발신 Call" fontWeight="bold" color="0x204c3f" fontFamily="굴림" fontSize="12" backgroundColor="#d7e8e3"
					 width="{(width)/4}" height="40" textAlign="center" verticalAlign="middle"
					 * 
			 * */
			var l:Label = new Label;
			axisHBox.removeAllChildren();
			axisVBox.removeAllChildren();
			
			for(var i:int = 0;i<=sector;i++)
			{
				l = new Label;
				
				l.width = xgap - 5;
				l.height = bgHeight;
				l.text = getVerticalAxisName(maxValue / sector * (i));
				l.y = topmargin+bgHeight*(sector-i) - 3;
					
				l.setStyle("fontSize",10);
				l.setStyle("fontFamily","tahoma");
				l.setStyle("verticalAlign","top");
				l.setStyle("textAlign","right");
				axisVBox.addChild(l);
			}
			
			var horizentalAxisLength:int = int(graphWidth/hAxiwWidth  );
			trace("horizentalAxisLength",horizentalAxisLength);
			for( i = 0;i<horizentalAxisLength;i++)
			{
				
				l = new Label;
				l.width = hAxiwWidth;
				l.height = axisHBox.height;
				l.text = getHorizontalAxisName(graphData.length /horizentalAxisLength * i );
				l.setStyle("fontSize",10);
				l.setStyle("fontFamily","tahoma");
				l.setStyle("verticalAlign","middle");
				l.setStyle("textAlign","center");
				axisHBox.addChild(l)
			}
			
			var beforeValue:String;
			for(var t:int = 0;t<seriseFieldName.length;t++)
			{
				
				graphics.lineStyle(2,strokeArray[t]);
				for( i=0 ; i<graphData.length;i++)
				{
					
					var h:Number = xgap+lineXPoint * i+2;
					var value:String = graphData[i][seriseFieldName[t]];
					var v:Number = graphHeight-int(value) *lineYPoint;
					if(i>0)
						beforeValue = value;
					//trace(v , value);
					if(i==0)
						graphics.moveTo(h,topmargin+v);
					else if(value == "-")
						graphics.moveTo(h,topmargin+v);
					else if(value == "0" && !zeroView)
						graphics.moveTo(h,topmargin+v);
					else
						graphics.lineTo(h,topmargin+v);
						
				}
				
			}
		}
		
		private function getHorizontalAxisName(index:int):String
		{
			var r:String = graphData[index].time.split(" ")[1];
			var tm:Array = r.split(":");
			tm.pop();
				
			r = tm.join(":");
			return r;
		}
		protected function getVerticalAxisName(value:Number):String
		{
			var fommater:CurrencyFormatter = new CurrencyFormatter;
			fommater.currencySymbol ="";
			
			if(value == 0)
				return value.toString();
			
			return fommater.format(getFixed(value));
		}
		
		protected function getFixed(value:Number):String
		{
			// TODO Auto Generated method stub
			return value.toFixed();
		}
		private function getGraphObject(index:int):Object
		{
			var obj:Object = new Object;
			for (var i:int = 0;i<seriseData.length;i++)
			{
				var sd:LineSeriesData = seriseData[i] as LineSeriesData;
				var fdName:String = sd.data;
				obj[fdName] = _data[fdName][i];
			}
			obj.time = _data.time[i].split(" ")[1];
			return obj;
		}
	}
}